package security.core.filter.handler.impl;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import security.core.filter.handler.LoginProcessHandler;
import security.core.manager.AuthenticationManager;
import security.core.source.UserDetail;
import security.debug.RBACLogger;

public class RBACLoginProcessHandler implements LoginProcessHandler {

	@Override
	public Boolean login(ServletRequest request, ServletResponse response,
			AuthenticationManager authenticationManager) throws IOException,
			ServletException {
		// TODO Auto-generated method stub
		if (RBACLogger.debug()) {
			RBACLogger.log("RBACLoginProcessHandler#login is called!");
			RBACLogger.log("loging in!");
		}
		String username = ((HttpServletRequest)request).getParameter("rbac-username");
		String password = ((HttpServletRequest)request).getParameter("rbac-password");
		if (username != null && password != null) {
			UserDetail user = authenticationManager.authenticateUser(username, password);
			if (user != null) {
				// save session context
				HttpSession session = ((HttpServletRequest)request).getSession();
				session.setAttribute("RBAC_USER_DETAIL", user);
				return true;
			}
		}
		return false;
	}

}
